package com.miyu.book.controller.bookMagic;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miyu.book.pojo.BookRuleSet;
import com.miyu.book.service.bookMagic.BookMagicService;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
@RestController
@RequestMapping("/bookMagic")
public class BookMagic {

    @Autowired
    private BookMagicService bas;

    /**
     * 规则查询
     * @param param
     * @return
     */
    @RequestMapping("/queryRuleSet")
    public List<BookRuleSet> queryRuleSet (@RequestBody JSONObject param){
        return bas.queryRuleSet(param);
    }
    /**
     * 根据配置规则搜索数据
     * @param param
     * @return
     */
    @RequestMapping("/searchBook")
    public JSONArray searchBook(@RequestBody JSONObject param){
        JSONArray rs =  bas.searchBook(param);
        return rs;
    }

    /**
     * 获取数据章节+数据详情
     * @param param
     * @return
     */
    @RequestMapping("/queryDetailBookList")
    public JSONObject queryDetailBookList(@RequestBody JSONObject param){
        //  String bookId = param.getString("bookId");
        JSONObject rs = bas.queryDetailBookList(param);

        return rs;
    }

    /**
     * 阅读小说
     * @param param
     * @return
     */
    @RequestMapping("readBook")
    public JSONObject readBook(@RequestBody JSONObject param){
        return  bas.readBook(param);
    }

    /**
     * 下载分为 有下载地址 和服务器下载
     * 有下载地址的直接读取流文件下载
     * 无下载地址 直接读取服务网站连接下载
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("downloadFile")
    public HttpServletResponse downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String param = StringEscapeUtils.unescapeJavaScript(request.getParameter("content").trim());
        JSONObject para = JSONObject.parseObject(param);
        JSONObject jsonObject = JSONObject.parseObject(StringEscapeUtils.unescapeJavaScript(param));
        //有具体下载链接接入原网站下载
        if(para.containsKey("bookDown")){
            String url = para.getString("bookDown");
            String bookName = url.substring(url.lastIndexOf("/")+1,url.lastIndexOf("."))+url.substring(url.lastIndexOf("."));
            url=new String(url.getBytes("utf-8"),"utf-8");
            Connection.Response execute = null;
            execute = Jsoup.connect(url).timeout(100000).maxBodySize(0).ignoreContentType(true).execute();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(bookName.getBytes("utf-8"),"ISO8859-1"));
            response.setContentType("application/octet-stream");
            OutputStream out=  response.getOutputStream();
            out.write(execute.bodyAsBytes());
            out.close();
            return null;
        }


        String path = bas.downloadFile(para); //生成临时文件以供下载
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));

            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            int count =0;
            byte[] by = new byte[1024];
            //通过response对象获取OutputStream流
            OutputStream out=  response.getOutputStream();

            while((count=fis.read(by))!=-1){
                out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            fis.close();
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }


    @RequestMapping("initBook")
    public JSONObject initBook(@RequestBody JSONObject param){
        return bas.initBook(param);
    }


    /**
     * 验证码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("checkImg")
    public HttpServletResponse checkImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(150, 50, 6, 20);
       // ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 50, 4, 4);
    //ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
    //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
        return null;
    }
}
